#!/usr/bin/env python
# -*- mode: python; coding: utf-8; indent-tabs-mode: nil -*-
# vim: set filetype=python fileencoding=utf-8 expandtab sw=4 sts=4:

import sys
import os
from optparse import OptionParser, OptionGroup, SUPPRESS_HELP, SUPPRESS_USAGE

class MyCallback(object):
    def __init__(self):
        self.counter = 0
    def __call__(self, option, opt, val, parser):
        self.counter += 1
        print "--- MyCallback --- " + str(self.counter) + ". time called"
        print "--- MyCallback --- option.action(): " + option.action
        print "--- MyCallback --- option.type(): " + (option.type if option.type else "")
        print "--- MyCallback --- opt: " + opt
        print "--- MyCallback --- val: " + (val if val else "")
        print "--- MyCallback --- parser.usage(): " + parser.usage
        print

def main():
    usage = \
        "usage: %prog [OPTION]... DIR [FILE]..." \
        if "DISABLE_USAGE" not in os.environ else \
        SUPPRESS_USAGE
    version = (
        "%prog 1.0\nCopyright (C) 2010 Johannes Weißl\n"
        "License GPLv3+: GNU GPL version 3 or later "
        "<http://gnu.org/licenses/gpl.html>.\n"
        "This is free software: you are free to change and redistribute it.\n"
        "There is NO WARRANTY, to the extent permitted by law."
    )
    desc = (
        "Lorem ipsum dolor sit amet, consectetur adipisicing"
        " elit, sed do eiusmod tempor incididunt ut labore et dolore magna"
        " aliqua.\nUt enim ad minim veniam, quis nostrud exercitation ullamco"
        " laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor"
        " in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla"
        " pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa"
        " qui officia deserunt mollit anim id est laborum."
    )
    epilog = (
        "Sed ut perspiciatis unde omnis iste natus error sit"
        " voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque"
        " ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae"
        " dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit"
        " aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos"
        " qui ratione voluptatem sequi nesciunt.\nNeque porro quisquam est, qui"
        " dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia"
        " non numquam eius modi tempora incidunt ut labore et dolore magnam"
        " aliquam quaerat voluptatem."
    )

    parser = OptionParser(
        usage=usage,
        version=version,
        description=desc,
        epilog=epilog
    )
    if "DISABLE_INTERSPERSED_ARGS" in os.environ:
        parser.disable_interspersed_args()

    parser.set_defaults(verbosity="50")
    parser.set_defaults(no_clear=False)

    parser.add_option("--clear", action="store_false", dest="no_clear", help="clear (default)")
    parser.add_option("--no-clear", action="store_true", help="not clear")
    parser.add_option("--string",
        help="This is a really long text... very long indeed! It must be wrapped on normal terminals.")
    parser.add_option("-x", "--clause", "--sentence", metavar="SENTENCE", default="I'm a sentence",
        help="This is a really long text... very long indeed! It must be wrapped on normal terminals. "
             "Also it should appear not on the same line as the option.")
    parser.add_option("-k", action="count", help="how many times?")
    parser.add_option("--verbose", action="store_const", const="100", dest="verbosity", help="be verbose!")
    parser.add_option("-s", "--silent", action="store_const", const="0", dest="verbosity", help="be silent!")
    parser.add_option("-n", "--number", type="int", default=1, metavar="NUM", help="number of files (default: %default)")
    parser.add_option("-H", action="help", help="alternative help")
    parser.add_option("-V", action="version", help="alternative version")
    parser.add_option("-i", "--int", action="store", type="int", default=3, help="default: %default")
    parser.add_option("-f", "--float", action="store", type="float", default=5.3, help="default: %default")
    parser.add_option("-c", "--complex", action="store", type="complex")
    choices = ["foo", "bar", "baz"]
    parser.add_option("-C", "--choices", choices=choices)
    choices_list = ["item1", "item2", "item3"]
    parser.add_option("--choices-list", choices=choices_list)
    parser.add_option("-m", "--more", action="append")
    parser.add_option("--more-milk", action="append_const", const="milk")
    parser.add_option("--hidden", help=SUPPRESS_HELP)

    # test for 325cb47
    parser.add_option("--option1", action="store", type="int", default=1)
    parser.add_option("--option2", action="store", type="int", default="1")
    parser.set_defaults(option1="640")
    parser.set_defaults(option2=640) # now works

    mc = MyCallback()
    parser.add_option("-K", "--callback", action="callback", callback=mc, help="callback test")
    parser.add_option("--string-callback", action="callback", callback=mc, type="string", help="callback test")

    group1 = OptionGroup(parser, "Dangerous Options",
        "Caution: use these options at your own risk. "
        "It is believed that some of them\nbite.")
    group1.add_option("-g", action="store_true", help="Group option.", default=False)
    parser.add_option_group(group1)

    group2 = OptionGroup(parser, "Size Options", "Image Size Options.")
    group2.add_option("-w", "--width", action="store", type="int", default=640, help="default: %default")
    group2.add_option("--height", action="store", type="int", help="default: %default")
    parser.set_defaults(height=480)
    parser.add_option_group(group2)

    options, args = parser.parse_args()

    print "clear:", ("false" if options.no_clear else "true")
    print "string:", options.string if options.string else ""
    print "clause:", options.clause
    print "k:", options.k if options.k else ""
    print "verbosity:", options.verbosity
    print "number:", options.number
    print "int:", options.int
    print "float: %g" % (options.float,)
    c = complex(0)
    if options.complex is not None:
        c = options.complex
    print "complex: (%g,%g)" % (c.real, c.imag)
    print "choices:", options.choices if options.choices else ""
    print "choices-list:", options.choices_list if options.choices_list else ""
    print "more:",
    print ", ".join(options.more if options.more else [])

    print "more_milk:"
    for opt in (options.more_milk if options.more_milk else []):
        print "-", opt

    print "hidden:", options.hidden if options.hidden else ""
    print "group:", ("true" if options.g else "false")

    print "option1:", options.option1
    print "option2:", options.option2

    print "width:", options.width
    print "height:", options.height

    print
    print "leftover arguments: "
    for arg in args:
        print "arg: " + arg

    return 0

if __name__ == "__main__":
    main()
